package com.fare.taluo.action.price.rubik;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.foreveross.hbase.client.HBaseHelper;
import org.foreveross.hbase.client.HBasePlaneinfoHelper;
import org.springframework.stereotype.Service;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.plane.city.PortApplication;
import com.fare.taluo.application.report.air.AirChinaTaobaoApplication;
import com.fare.taluo.application.system.email.EmailSendApplication;
import com.fare.taluo.application.system.email.ReportEmailApplication;
import com.fare.taluo.core.domain.queue.message.QueueEmailMessageEntity;
import com.fare.taluo.queue.ExcelTaobao;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.vo.core.PlaneInfo;
import com.fare.taluo.vo.core.PortEntityVO;
import com.fare.taluo.vo.reportemail.EmailVO;
import com.fare.taluo.vo.taobaoPriceRubik.TaobaoPriceRubikVO;
import com.fare.util.ReportProperties;


/*
 * （国内）价格魔方模板-淘宝
*/
@Service
public class PriceRubikAction {
	
	@Resource(name="portApplication")	
	private PortApplication portApplication;
	
	@Resource(name ="airChinaTaobaoApplication")
	private AirChinaTaobaoApplication airChinaTaobaoApplication;
	
	/*
	 * 1.生成excel模版
	 * 2.查询Hbase数据
	 * 3.插入数据到excel
	*/
	private String fromAndTocityKey;//出发城市和到达城市的KEY
	private String flightNoKey;//航班号Key
	private String grabChannelKey;//渠道Key
	private String flightDateKey;//航班日期Key
	private Date flightDate;//未来航班日期
	private String startRowKey;
	private String endRowKey;
	private String pretrementTable;//查找表
	private List<PlaneInfo> allList;
	private String email = null;
	
	@Resource(name ="reportEmailApplication")
	private ReportEmailApplication reportEmailApplication;
	
	
	private List<EmailVO> emailList;
	private String getTeger;
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public List<EmailVO> getEmailList() {
		return emailList;
	}

	public void setEmailList(List<EmailVO> emailList) {
		this.emailList = emailList;
	}

	public void execute() throws Exception{
		try{
		//获取后台要发送的Email
		if(email==null || email==""){
			emailList=reportEmailApplication.findAllEmail(1);//0表示不接受状态，1表示接受状态
			StringBuffer emailStr=new StringBuffer();
			for(EmailVO emailVo:emailList){
				emailStr.append(","+emailVo.getEmailAddress());
			}
			if(emailStr.length()>1 && emailStr !=null){
				email=emailStr.toString().substring(1);
			}
		}
		String title = "国航淘宝旗舰店与代理人差价报表_"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		ExcelTaobao.taobaoExcel(title,getDataByHbase() ,getTeger);

		QueueEmailMessageEntity email = new QueueEmailMessageEntity();

		String strFilePath = ReportProperties.getInstance().getSavePath().endsWith("/")? ReportProperties.getInstance().getSavePath() :	ReportProperties.getInstance().getSavePath()+"/";
		String strFileName = strFilePath+title+ ".xls";
		if(StringUtils.isNotBlank(getEmail())){
			email.setAttachPath(strFileName);//new String(location.getBytes("ISO8859-1"),"UTF-8")//new String(location.getBytes("UTF-8"),"ISO8859-1")
			email.setBody("<p>您好!<p><p>&nbsp;&nbsp;已生成您需要的淘宝旗舰店与代理人差价报表，详情请查看收附件。</p>");//正文
			email.setSubject(title);//主题
			email.setToAddress(getEmail());
			email.setName(title);
			InstanceFactory.getInstance(EmailSendApplication.class).save(email);
		}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
	}
	
	public Map<String, Map<String, List<TaobaoPriceRubikVO>>> getDataByHbase() throws Exception{
	//	PortApplication portApplication=new PortApplicationImpl();
		String grabDateFormat = "yyyy-MM-dd";
		Map <String,Map<String ,List<TaobaoPriceRubikVO>>> allDatas=new java.util.HashMap<String,Map<String ,List<TaobaoPriceRubikVO>>>();
		List<String> getAllGrabDate=new ArrayList<String>();
		String dates="";
		String citys="";
		/*
		 * 1.根据表中数据，组装rowKey，表为:LP_FLIGHT；
		 * 2.根据rowKey，取出所有的数据，然后对比筛选（最低价）；
		 * 3.报表需要的数据包括：代理人最低价(含20元保险），旗舰店，旗舰店-淘宝差价
		 * 航班最低价LP_FLIGHT：  渠道_起点(使用三字码)_终点(使用三字码)_(航班号)_航班日期(年月日时)
		 * HBaseHelper.delRecord("LP_FLIGHT", "20004PEKHAK00HU73822013051613");//20004 PEK HAK 00 HU7382 2013051613
		 * startKey = grabChannel + fromCityStr + toCityStr + "00"+ flightNumber + flightStartTime + "00";
		 * endKey = grabChannel + fromCityStr + toCityStr + "00"+ flightStopNum + flightEndTime + "24";
		 * 传入的数据格式：Map <String,Map<String ,List<TaobaoPriceRubikVO>>> listValue
		*/
		
		//初始化航线
		String [] linesList ={"PEKCTU","CKGPEK","CANCTU","XIYPEK","HGHXMN","HGHCKG","CANCKG","LXACTU","XMNPEK","SHEPEK"};
		//初始化八大航空公司
		String [] carrier_keys={"CA","CZ","MU","SC","3U","HU","ZH","MF"};
		
		String [] futureDate={"7","16","34"};
		//初始化渠道
		grabChannelKey="00001";//淘宝旅游
		//组装rowKey
		pretrementTable="LP_FLIGHT";
		String getCarrier_key=null;
		
		for(int i=0;i<linesList.length;i++){
			fromAndTocityKey=linesList[i];
			String fromCity=fromAndTocityKey.substring(0, 3);
			String toCity=fromAndTocityKey.substring(3);
			citys=fromCity+"-"+toCity;
			PortEntityVO vo = portApplication.findCityNameByPortCode(fromCity);
			System.out.println(vo);
			String fromCityName=portApplication.findCityNameByPortCode(fromCity).getCityName();
			String toCityName=portApplication.findCityNameByPortCode(toCity).getCityName();
			citys=fromCityName+"-"+toCityName;
			Map<String ,List<TaobaoPriceRubikVO>> lineDatas=new java.util.HashMap<String ,List<TaobaoPriceRubikVO>>();
			for(int dateNum=0;dateNum<futureDate.length;dateNum++){
				 List<TaobaoPriceRubikVO> getAllLists=new ArrayList<TaobaoPriceRubikVO>();
				 dates=futureDate[dateNum];
				 Calendar c = Calendar.getInstance();  
				 c.setTime(new Date());   //设置当前日期   
//				 c.setTime(DateUtils.strToDate("2014-02-26", "yyyy-MM-dd"));
				 c.add(Calendar.DATE, Integer.parseInt(dates));
				 flightDate= c.getTime();
				for(int carrierSizes=0;carrierSizes<carrier_keys.length;carrierSizes++){
					List<TaobaoPriceRubikVO> allLists=new ArrayList<TaobaoPriceRubikVO>();
					List<Filter> filterList = new ArrayList<Filter>();
					getCarrier_key=carrier_keys[carrierSizes];
					
					flightDateKey=DateUtils.formatDay(flightDate,grabDateFormat);
					SingleColumnValueFilter singleFilter = new SingleColumnValueFilter("planeinfo".getBytes(), "carrierKey".getBytes(), CompareOp.EQUAL, getCarrier_key.getBytes());
					SingleColumnValueFilter singleFilter2 = new SingleColumnValueFilter("planeinfo".getBytes(), "flightBatchDate".getBytes(), CompareOp.EQUAL, flightDateKey.getBytes());
					filterList.add(singleFilter);
				 	filterList.add(singleFilter2);
				 	//此为Hbase查找方式
				 	/*ResultScanner scan = HBaseHelper.getRecords(pretrementTable, StringUtils.rightPad(grabChannelKey+fromAndTocityKey, 29, "0"),	
					StringUtils.rightPad(grabChannelKey+fromAndTocityKey, 29, "Z"),new String[]{"planeinfo","agentInfos"},filterList);
				 	try {
				 		allLists = HBasePlaneinfoHelper.transformHBaseResultToTaobaoPriceRubikVOs(scan);
				 	} catch (Exception e) {
						e.printStackTrace();
					}*/
				 	
				 	//此为mysql取数据
				 	String reportDateStr=DateUtils.getDateStr("yyyy-MM-dd");
//				 	reportDateStr="2014-02-26";
				 	Date reportDate= DateUtils.strToDate(reportDateStr, "yyyy-MM-dd");
				 	flightDate= DateUtils.strToDate(flightDateKey, "yyyy-MM-dd");
				 	try{
				 		allLists=airChinaTaobaoApplication.findByCondition(reportDate, flightDate, fromCity, toCity, null, getCarrier_key, null);
				 	}catch (Exception e) {
				 		e.printStackTrace();
					}
				 
					if (allLists.size() > 0) {
						/*for (int agb = 0; agb < allLists.size(); agb++) {
							String grabDateStr = allLists.get(agb)
									.getGrabDate();
							getAllGrabDate.add(grabDateStr);
						}*/
						getAllLists.addAll(allLists);
					}
			} 
				if(getAllLists.size()>0){
					lineDatas.put(dates, getAllLists);
				}
		}
			 if(lineDatas.values().size()>0){
				 allDatas.put(citys, lineDatas);
			 }
		}
		//排序抓取日期
		Long forTestMin=99999999999999999L;
		Long forTestMax=0L;
		
		for(int forFL=0;forFL<getAllGrabDate.size();forFL++){
			if(Long.parseLong(getAllGrabDate.get(forFL))<forTestMin){
				forTestMin=Long.parseLong(getAllGrabDate.get(forFL));
			}
		}
		for(int forFL=0;forFL<getAllGrabDate.size();forFL++){
			if(Long.parseLong(getAllGrabDate.get(forFL))>forTestMax){
				forTestMax=Long.parseLong(getAllGrabDate.get(forFL));
			}
		}
		DateFormat format = new SimpleDateFormat("yyyyMMddHH");
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH");//24小时制  
        Date date_1=null;
        Date date_2=null;
		String forTestMinStr= forTestMin.toString().substring(0,10);
		String forTestMaxStr=null;
		if(forTestMax==0){
			forTestMaxStr="0000000000";
		}else{
			forTestMaxStr=forTestMax.toString().substring(0,10);
		}
		try {
			date_1=format.parse(forTestMinStr);
			date_2=format.parse(forTestMaxStr);
		} catch (ParseException e1) {
			e1.printStackTrace();
		} 
		String forTestMinStr_s=sdformat.format(date_1).replace(" ", "日")+"时";
		String forTestMaxStr_s=sdformat.format(date_2).replace(" ", "日")+"时";
		getTeger=forTestMinStr_s+"_"+forTestMaxStr_s;
		System.out.println("getAllGrabDate="+getTeger);
		//处理没有数据的航线，如果没有数据，就插入一条空数据，并在报表中显示
		if(allDatas.keySet().size()<linesList.length){
			Map<String ,List<TaobaoPriceRubikVO>> noDatasMap=new java.util.HashMap<String ,List<TaobaoPriceRubikVO>>();
			List<TaobaoPriceRubikVO> noDatasList=new ArrayList<TaobaoPriceRubikVO>();
			TaobaoPriceRubikVO noDatasVo=new TaobaoPriceRubikVO();
			List<String >linesLists=new ArrayList<String >();
			noDatasVo.setAgentLowerPrice("");
			noDatasVo.setLowerPrice("");
			noDatasVo.setFlightId("");
			noDatasVo.setDifferencePirce("");
			noDatasList.add(noDatasVo);
			noDatasMap.put("7", noDatasList);
			noDatasMap.put("16", noDatasList);
			noDatasMap.put("34", noDatasList);
			for(int l=0;l<linesList.length;l++){
				String fromCityKey=linesList[l].substring(0, 3);
				String toCityKey=linesList[l].substring(3);
				String fromCityNames=portApplication.findCityNameByPortCode(fromCityKey).getCityName();
				String toCityNames=portApplication.findCityNameByPortCode(toCityKey).getCityName();
				linesLists.add(fromCityNames+"-"+toCityNames);
			}
			for(int k=0;k<linesLists.size();k++){
				if(allDatas.get(linesLists.get(k)) ==null ||allDatas.get(linesLists.get(k)).values().size()<0 || allDatas.get(linesLists.get(k)).values().equals("") || allDatas.get(linesLists.get(k)).values()==null){
					allDatas.put(linesLists.get(k), noDatasMap);
				}
			}
		}
		return allDatas;
	}
	
	public static void main(String[] args){
		PortApplication portApplication;
		
		Map <String,Map<String ,List<TaobaoPriceRubikVO>>> allDatas=new java.util.HashMap<String,Map<String ,List<TaobaoPriceRubikVO>>>();
		List<PlaneInfo> allList =new ArrayList<PlaneInfo>();
		String grabDateFormat = "yyyy-MM-dd";
		String [] linesList ={"PEKCTU","CKGPEK","CANCTU","XIYPEK","HGHXMN","HGHCKG","CANCKG","LXACTU","XMNPEK","SHEPEK"};
		//初始化八大航空公司
		String [] carrier_keys={"CA","CZ","MU","SC","3U","HU","ZH","MF"};
		//初始化日期
		String dates=null;
		String citys="";
		   
		String [] futureDate={"7","16","34"};
		//初始化渠道
		String grabChannelKey="00001";//淘宝旅游
		//组装rowKey
		String pretrementTable="LP_FLIGHT";
		String startRowKey=null;
		String endRowKey=null;
		String getCarrier_key=null;
		 String flightDateKey=null;
		 List<String> getAllGrabDate=new ArrayList<String>();
		for(int i=0;i<linesList.length;i++){
			
			String fromAndTocityKey=linesList[i];
			String fromCity=fromAndTocityKey.substring(0, 3);
			String toCity=fromAndTocityKey.substring(3);
//			String fromCityName=portApplication.findPortEntityByCityName(fromCity).getPortCode();
//			String toCityName=portApplication.findPortEntityByCityName(toCity).getPortCode();
			citys=fromCity+"-"+toCity;
			Map<String ,List<TaobaoPriceRubikVO>> lineDatas=new java.util.HashMap<String ,List<TaobaoPriceRubikVO>>();
			Map<String ,List<TaobaoPriceRubikVO>> lineDatasNodata=new java.util.HashMap<String ,List<TaobaoPriceRubikVO>>();
			 for(int dateNum=0;dateNum<futureDate.length;dateNum++){
				 List<TaobaoPriceRubikVO> getAllLists=new ArrayList<TaobaoPriceRubikVO>();
				 dates=futureDate[dateNum];
				 Calendar c = Calendar.getInstance();  
			        c.setTime(new Date());   //设置当前日期
					c.add(Calendar.DATE, Integer.parseInt(dates));
					Date flightDate= c.getTime();
					flightDateKey=DateUtils.formatDay(flightDate,grabDateFormat);
				for(int carrierSizes=0;carrierSizes<carrier_keys.length;carrierSizes++){
					List<TaobaoPriceRubikVO> allLists=new ArrayList<TaobaoPriceRubikVO>();
				 List<Filter> filterList = new ArrayList<Filter>();
				getCarrier_key=carrier_keys[carrierSizes];
				
				 SingleColumnValueFilter singleFilter = new SingleColumnValueFilter("planeinfo".getBytes(), "carrierKey".getBytes(), CompareOp.EQUAL, getCarrier_key.getBytes());
				 SingleColumnValueFilter singleFilter2 = new SingleColumnValueFilter("planeinfo".getBytes(), "flightBatchDate".getBytes(), CompareOp.EQUAL, flightDateKey.getBytes());
				 filterList.add(singleFilter2);
				 filterList.add(singleFilter);
//				 String test=StringUtils.rightPad(grabChannelKey+fromAndTocityKey, 29, "0");
//				 String endtest=StringUtils.rightPad(grabChannelKey+fromAndTocityKey, 29, "Z");
//				 System.out.println("startRowkey=="+test+"  endtest="+endtest);
				 ResultScanner scan=null;
				try {
					scan = HBaseHelper.getRecords(pretrementTable, StringUtils.rightPad(grabChannelKey+fromAndTocityKey, 29, "0"),	
							StringUtils.rightPad(grabChannelKey+fromAndTocityKey, 29, "Z"),new String[]{"planeinfo","agentInfos"},filterList);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//				HBaseHelper.printResult(scan);
				 try {
					allLists = HBasePlaneinfoHelper.transformHBaseResultToTaobaoPriceRubikVOs(scan);
				} catch (Exception e) {
					e.printStackTrace();
				}
				 //获取所有的抓取时间
				 if(allLists.size()>0){
					 for(int agb=0;agb<allLists.size();agb++){
						 String grabDateStr=allLists.get(agb).getGrabDate();
						 getAllGrabDate.add(grabDateStr);
					 }
					
				 getAllLists.addAll(allLists);
				 }
				 
				}
				System.out.println(""+getAllLists.size());
				if(getAllLists.size()>0){
					lineDatas.put(dates, getAllLists);
				}
				
			}
			 if(lineDatas.values().size()>0){
				 allDatas.put(citys, lineDatas);
			 }
		}
		//排序抓取日期
		Long forTestMin=99999999999999999L;
		Long forTestMax=0L;
		
		for(int forFL=0;forFL<getAllGrabDate.size();forFL++){
			if(Long.parseLong(getAllGrabDate.get(forFL))<forTestMin){
				forTestMin=Long.parseLong(getAllGrabDate.get(forFL));
			}
		}
		for(int forFL=0;forFL<getAllGrabDate.size();forFL++){
			if(Long.parseLong(getAllGrabDate.get(forFL))>forTestMax){
				forTestMax=Long.parseLong(getAllGrabDate.get(forFL));
			}
		}
		DateFormat format = new SimpleDateFormat("yyyyMMddHH");
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH");//24小时制  
        Date date_1=null;
        Date date_2=null;
		String forTestMinStr= forTestMin.toString().substring(0,10);
		String forTestMaxStr=null;
		if(forTestMax==0){
			forTestMaxStr="0000000000";
		}else{
			forTestMaxStr=forTestMax.toString().substring(0,10);
		}
		try {
			date_1=format.parse(forTestMinStr);
			date_2=format.parse(forTestMaxStr);
		} catch (ParseException e1) {
			e1.printStackTrace();
		} 
		String forTestMinStr_s=sdformat.format(date_1).replace(" ", "日")+"时";
		String forTestMaxStr_s=sdformat.format(date_2).replace(" ", "日")+"时";
		String getTegers=forTestMinStr_s+"_"+forTestMaxStr_s;
	//	System.out.println("getAllGrabDate="+getTeger);
		
		//处理没有数据的航线，如果没有数据，就插入一条空数据，并在报表中显示
		if(allDatas.keySet().size()<linesList.length){
			Map<String ,List<TaobaoPriceRubikVO>> noDatasMap=new java.util.HashMap<String ,List<TaobaoPriceRubikVO>>();
			List<TaobaoPriceRubikVO> noDatasList=new ArrayList<TaobaoPriceRubikVO>();
			TaobaoPriceRubikVO noDatasVo=new TaobaoPriceRubikVO();
			noDatasVo.setAgentLowerPrice("");
			noDatasVo.setLowerPrice("");
			noDatasVo.setFlightId("");
			noDatasVo.setDifferencePirce("");
			noDatasList.add(noDatasVo);
			noDatasMap.put("7", noDatasList);
			noDatasMap.put("16", noDatasList);
			noDatasMap.put("34", noDatasList);
			List<String >linesLists=new ArrayList<String >();
			for(int l=0;l<linesList.length;l++){
				String fromCityKey=linesList[l].substring(0, 3);
				String toCityKey=linesList[l].substring(3);
				linesLists.add(fromCityKey+"-"+toCityKey);
			}
			for(int k=0;k<linesLists.size();k++){
				if(allDatas.get(linesLists.get(k)) ==null ||allDatas.get(linesLists.get(k)).values().size()<0 || allDatas.get(linesLists.get(k)).values().equals("") || allDatas.get(linesLists.get(k)).values()==null){
					allDatas.put(linesLists.get(k), noDatasMap);
				}
			}
		}
		
		try {
			ExcelTaobao.taobaoExcel("（国内）价格魔方-淘宝 ", allDatas,getTegers);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

	public String getFromAndTocityKey() {
		return fromAndTocityKey;
	}

	public void setFromAndTocityKey(String fromAndTocityKey) {
		this.fromAndTocityKey = fromAndTocityKey;
	}

	public String getFlightNoKey() {
		return flightNoKey;
	}

	public void setFlightNoKey(String flightNoKey) {
		this.flightNoKey = flightNoKey;
	}

	public String getGrabChannelKey() {
		return grabChannelKey;
	}

	public void setGrabChannelKey(String grabChannelKey) {
		this.grabChannelKey = grabChannelKey;
	}

	public String getFlightDateKey() {
		return flightDateKey;
	}

	public void setFlightDateKey(String flightDateKey) {
		this.flightDateKey = flightDateKey;
	}

	public Date getFlightDate() {
		return flightDate;
	}

	public void setFlightDate(Date flightDate) {
		this.flightDate = flightDate;
	}

	public String getStartRowKey() {
		return startRowKey;
	}

	public void setStartRowKey(String startRowKey) {
		this.startRowKey = startRowKey;
	}

	public String getEndRowKey() {
		return endRowKey;
	}

	public void setEndRowKey(String endRowKey) {
		this.endRowKey = endRowKey;
	}

	public String getPretrementTable() {
		return pretrementTable;
	}

	public void setPretrementTable(String pretrementTable) {
		this.pretrementTable = pretrementTable;
	}

	public List<PlaneInfo> getAllList() {
		return allList;
	}

	public void setAllList(List<PlaneInfo> allList) {
		this.allList = allList;
	}
	
	
}
